package com.jianyun.jyzs.http;

import android.text.TextUtils;
import android.util.Log;


import com.jianyun.jyzs.bean.CrmCountResponse;
import com.jianyun.jyzs.bean.CrmDetial;
import com.jianyun.jyzs.bean.CrmListResponse;
import com.jianyun.jyzs.bean.CrmPhoneNumBean;
import com.jianyun.jyzs.bean.CrmSearchBean;
import com.jianyun.jyzs.dao.CrmDao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.jianyun.jyzs.utils.RceLog;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by mlli on 2017/11/21.
 */

public class CrmHttpHelper {

    private static List<CrmDetial> crmDetailList;
    private static HashMap<Integer, CrmDetial> crmDetialHashMap = new HashMap<>();
    private static HashMap<String, Integer> mHashmap = new HashMap<String, Integer>();

   /* public static void getCrmList(final CrmDao crmDao, final String userId, int page, final CrmSyncListener listener) {
        Api api = RetrofitHelper.builderbch().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("page", page + "");
        api.getCrmList(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<CrmListResponse>() {
                    @Override
                    protected void onResponse(CrmListResponse response) {
                        RceLog.d("lml", "getCrmList=" + response.toString());
                        if (response.isResult()) {
                            List<CrmListResponse.CrmListBean> been = response.getList();
                            if (been.size() > 0) {
                                getCrmDetial(crmDao, been, userId, listener);
                            } else {
                                listener.synchroOver(true, null);
                            }
                        } else {
                            listener.synchroOver(false, response.getMessage().toString());
                        }


                    }

                    @Override
                    protected void onException(String msg) {

                    }
                });
    }*/

    private static int tag = 0;

    public interface CrmSyncListener {
        void synchroOver(boolean b, String msg);
    }

    /*public static void getCrmDetial(final CrmDao dao, final List<CrmListResponse.CrmListBean> selectedList, String userId, final CrmSyncListener listener) {
        try {
            Api api = RetrofitHelper.builderbch().create(Api.class);
            tag = 0;
            for (int i = 0; i < selectedList.size(); i++) {
                String id = selectedList.get(i).getId();
                api.getCrmDetial(userId, id)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new CustomCallback<CrmDetial>() {
                            @Override
                            protected void onResponse(CrmDetial response) {
                                RceLog.d("lml", "crm详情：" + response.getPo().getName());
                                tag += 1;
                                if (response.isResult()) {
                                    dao.insertCrm(response.getPo());
                                }
                                if (tag == selectedList.size())
                                    listener.synchroOver(true, null);
                            }

                            @Override
                            protected void onException(String msg) {
                                tag += 1;
                                RceLog.d("lml", msg);
                                if (tag == selectedList.size() & listener != null)
                                    listener.synchroOver(true, null);

                            }
                        });
            }
        } catch (Exception e) {

        }
    }*/

    public interface CrmCountListener {
        void syncCountResult(int count);
    }

    /*public static void getCrmCount(String userid, final CrmCountListener listener) {
        Api api = RetrofitHelper.builderbch().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userid);
        map.put("type", "0");
        api.getCrmCount(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<CrmCountResponse>() {
                    @Override
                    protected void onResponse(CrmCountResponse response) {
                        if (response.isResult()) {
                            int total = response.getTotal();
                            if (total > 0) listener.syncCountResult(total);
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                    }
                });
    }*/


    /**
     * 搜索crm的监听
     */
    public interface OnSearchCrmListLisenter {
        void onSearchSuccess(List<CrmSearchBean.ListCrm> list);
    }

    /**
     *
     */
    public interface OnGetPhoneNumLisenter {
        void onGetNumSuccess(HashMap<String, CrmPhoneNumBean.HasHData> hashMap);

        void onFaile(String msg);
    }

    public interface OnCrmDetailListenter {
        void onCrmListener(List<CrmSearchBean.ListCrm> listbean);

        void onEmtry();

        void onHintLoading();
    }

    /**
     * 搜索接口
     *
     * @param userid
     * @param pageIndex
     * @param pageSize
     * @param order
     * @param khzt
     * @param khxz
     * @param company
     * @param address
     */
    public static void searchCrmList(final String userid, String pageIndex, String pageSize, String order,
                                     String khzt, String khxz,
                                     String company, String address, final OnCrmDetailListenter onCrmDetailListenter) {
        Log.i("test", "userid:" + userid + "**p:" + pageIndex + "**p:" + pageSize + "**o:" + order + "**" + khzt + "**" + khxz + "**" + company + "**address:" + address);

        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "GetCRMList");
        map.put("saleid", userid);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        if (!TextUtils.isEmpty(order)) {
            map.put("order", order);
        }
        if (!TextUtils.isEmpty(khzt)) {
            map.put("khzt", khzt);
        }
        if (!TextUtils.isEmpty(khxz)) {
            map.put("khxz", khxz);
        }
        if (!TextUtils.isEmpty(company)) {
            map.put("company", company);
        }
        if (!TextUtils.isEmpty(address)) {
            map.put("address", address);
        }
        map.put("appCode","jyzs");
        map.put("appType","Android");
        map.put("appVersion","1.0.2");
        api.searchCrmList(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<CrmSearchBean>() {
                    @Override
                    protected void onResponse(CrmSearchBean response) {
                        RceLog.i("test", "搜索的：" + response.toString());
                        if (response.getResult()) {
                            int pageCut = Integer.parseInt(response.getPageCnt());
                            if (pageCut > 0) {
                                List<CrmSearchBean.ListCrm> list = response.getList();
                                if (list == null || list.size() == 0) {
                                    onCrmDetailListenter.onEmtry();
                                } else {
                                    onCrmDetailListenter.onCrmListener(list);
                                   // searchCrmListDetail(userid, list, onCrmDetailListenter);
                                }
                            } else {
                                onCrmDetailListenter.onEmtry();
                            }
                        } else {
                            onCrmDetailListenter.onHintLoading();
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        onCrmDetailListenter.onHintLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        onCrmDetailListenter.onHintLoading();
                        super.onError(e);
                    }
                });
    }

    static int flag = 0;

  /*  public static void searchCrmListDetail(String userId, final List<CrmSearchBean.ListCrm> list, final OnCrmDetailListenter onCrmDetailListenter) {
        try {
            Api api = RetrofitHelper.builderbch().create(Api.class);
            final int size = list.size();
            flag = 0;
            if (crmDetailList == null) {
                crmDetailList = new ArrayList<>();
            }
            crmDetailList.clear();
            mHashmap.clear();
            crmDetialHashMap.clear();
            for (int i = 0; i < size; i++) {
                String id = list.get(i).getAutoid() + "";
                mHashmap.put(id, i);
                api.getCrmDetial(userId, id)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new CustomCallback<CrmDetial>() {
                            @Override
                            protected void onResponse(CrmDetial response) {
                                try {
                                    flag += 1;
                                    if (null != response.getPo()) {
                                        String id1 = response.getPo().getId();
                                        int integer = mHashmap.get(id1);
                                        crmDetialHashMap.put(integer, response);
                                        if (flag == size) {
                                            for (int j = 0; j < crmDetialHashMap.size(); j++) {
                                                CrmDetial crmDetial = crmDetialHashMap.get(j);
                                                crmDetailList.add(crmDetial);
                                            }
                                            //onCrmDetailListenter.onCrmListener(crmDetailList);
                                        }
                                    }


                                } catch (Exception e) {
                                    e.printStackTrace();
                                    onCrmDetailListenter.onHintLoading();
                                }

                            }

                            @Override
                            protected void onException(String msg) {
                                onCrmDetailListenter.onHintLoading();
                            }
                        });
            }
        } catch (Exception e) {
            e.printStackTrace();
            onCrmDetailListenter.onHintLoading();
        }
    }*/

    public static void getCrmPhoneNum(String userId, final OnGetPhoneNumLisenter onGetPhoneNumLisenter) {
        Api api = RetrofitHelper.builderErpRoot().create(Api.class);
        api.getNewPhoneNum("crm_listmessage", userId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<CrmPhoneNumBean>() {
                    @Override
                    protected void onResponse(CrmPhoneNumBean response) {
                        Log.i("test", "crm_listmessage:" + response.toString());
                        if (response.getResult()) {
                            List<CrmPhoneNumBean.Data> data = response.getData();
                            HashMap<String, CrmPhoneNumBean.HasHData> hashMap = new HashMap<>();
                            for (CrmPhoneNumBean.Data listdata : data) {
                                hashMap.put(listdata.getId(), new CrmPhoneNumBean.HasHData(listdata.getPhoneTimes(), listdata.getVisitTimes()));
                            }
                            onGetPhoneNumLisenter.onGetNumSuccess(hashMap);
                        } else {
                            onGetPhoneNumLisenter.onFaile(response.getMessage());
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        onGetPhoneNumLisenter.onFaile(msg);
                    }
                });
    }

}
